import glob
import os
import subprocess


def shp_to_dm(shp_path):
    """
    将shp数据导入达梦数据库
    :param shp_path:
    :return:
    """
    # TODO 待优化
    shp_name = os.path.basename(shp_path)
    dir_name = os.path.dirname(shp_path)

    ctl_path = dir_name + "\\" + shp_name + ".ctl"
    clob_path = dir_name + "\\" + shp_name + ".lob"
    dmshp2st = 'D:\software\professional\dmdbms\\bin\dmshp2st.exe shapefile="{0}" table_name="{1}"'
    dmdldr = "D:\software\professional\dmdbms\\bin\dmfldr.exe userid=DLMIS1/egovaegova@localhost:5236 control='{0}' lob_directory='{1}' mode='IN' character_code='GBK' enable_class_type=true enable_class_type=true IGNORE_AIMLESS_DATA=true UNREP_CHAR_MODE=0 ERRORS=100000"
    dmshp2st_temp = dmshp2st.format(shp_path, shp_name)
    dmdldr_temp = dmdldr.format(ctl_path, clob_path)
    print(dmshp2st_temp)
    print(dmdldr_temp)


def shp_to_postgres(shp_path):
    """
    将shp数据导入postgres数据库
    create extension postgis 创建空间扩展
    D:\software\professional\QGIS 3.22.5\bin为qgis的安装路劲下的bin路径，使用其中的ogr2ogr文件进行数据导入
    :param shp_path:
    :return:
    """

    os.chdir(r"D:\software\professional\QGIS 3.22.5\bin")
    # cmd_str = r'ogr2ogr -f "PostgreSQL" PG:"host=localhost port=5432 dbname=changping user=postgres password=egova schemas=public" {0} -lco GEOMETRY_NAME=geom -lco FID=fid --config SHAPE_ENCODING "GBK" -nlt PROMOTE_TO_MULTI -nln {1}'
    cmd_str = r'ogr2ogr -f "PostgreSQL" PG:"host=localhost port=5432 dbname=test user=postgres password=egova schemas=public" {0} -lco GEOMETRY_NAME=geom -lco FID=gid --config SHAPE_ENCODING "GBK" -nlt PROMOTE_TO_MULTI -nln {1}'
    shp_name = os.path.basename(shp_path).split(".")[0].split("_")[-1]
    shp_to_db_cmd = cmd_str.format(shp_path, shp_name)
    print(shp_to_db_cmd)
    subprocess.run(shp_to_db_cmd, shell=True)


if __name__ == '__main__':
    for path in glob.glob(r"E:\data\房山\xinwangge\*.shp"):
        shp_to_postgres(path)
